<?php
namespace Core;

class Request {
    protected $method;
    protected $uri;
    protected $headers;
    protected $body;
    protected $query;
    protected $routeParams = [];
    
    public function __construct() {
        $this->method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
        $this->uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $this->headers = getallheaders();
        $this->body = $this->parseBody();
        $this->query = $_GET;
    }
    
    public function getMethod() {
        return $this->method;
    }
    
    public function getPath() {
        return $this->uri;
    }
    
    public function getHeaders() {
        return $this->headers;
    }
    
    public function getHeader($name) {
        return $this->headers[$name] ?? null;
    }
    
    public function getBody() {
        return $this->body;
    }
    
    public function getQuery() {
        return $this->query;
    }
    
    public function get($key, $default = null) {
        return $this->body[$key] ?? $this->query[$key] ?? $default;
    }
    
    public function setRouteParams($params) {
        $this->routeParams = $params;
    }
    
    public function getRouteParams() {
        return $this->routeParams;
    }
    
    // 只保留一个 getRouteParam 方法
    public function getRouteParam($name, $default = null) {
        return $this->routeParams[$name] ?? $default;
    }
    
    protected function parseBody() {
        $contentType = $this->getHeader('Content-Type') ?? '';
        
        if (strpos($contentType, 'application/json') !== false) {
            return json_decode(file_get_contents('php://input'), true) ?? [];
        }
        
        return $_POST;
    }
}